<script setup lang="ts">
import { computed, inject, onMounted, ref, watchEffect } from 'vue'
import { Emitter } from 'mitt'
import { storeToRefs } from 'pinia'
import { useToolStore } from '../stores/tool'

const props = defineProps<{
  version: {
    conda: string,
    python: string,
    url: string,
    platform: string,
    exist?: boolean
  }
}>()

const {
  selectedConda
} = storeToRefs(useToolStore())

const mittInstance: Emitter<any> | undefined = inject('mitt')
const platformClass = computed(() => {
  if (props.version.exist) {
    return 'installed'
  } else {
    if (props.version.platform.toLowerCase().startsWith('windows')) {
      return 'windows'
    } else {
      return 'linux'
    }
  }
})

const background = ref('#fff')

const choose = () => {
  mittInstance.emit('selectAnaconda', props.version)
  radio.value.checked = true
}

const radio = ref<HTMLInputElement | null>(null)

watchEffect(() => {
  if (radio.value && radio.value.checked) {
    background.value = '#8da1f2'
  } else {
    background.value = '#fff'
  }
})

onMounted(() => {
  if (selectedConda.value && selectedConda.value.url) {
    if (selectedConda.value.exist === props.version.exist) {
      if (selectedConda.value.url === props.version.url) {
        radio.value.checked = true
      }
    }
  }

})
</script>

<template>
  <div ref="card" @click="choose" class="select-none card border-2 border-black flex flex-col">
    <div class="h-full text-center flex flex-col justify-center gap-y-2">
      <div class="font-bold text-xl">python {{ props.version.python }}</div>
      <div> {{ props.version.conda }}</div>
      <div>{{ props.version.platform }}</div>
      <input ref="radio" type="radio" name="version" />
    </div>
    <div :class="platformClass"></div>
  </div>
</template>

<style scoped>
.card {
  width: 200px;
  height: 180px;
  background-color: v-bind(background);
}

.windows {
  width: 100%;
  height: 65px;
  background-image: url("../assets/windows.png");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
}

.linux {
  width: 100%;
  height: 65px;
  background-image: url("../assets/linux.png");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
}

.installed {
  width: 100%;
  height: 65px;
  background-image: url("../assets/installed.png");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
}
</style>